<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仓仓管家 - 仓库管理</title>
    <!-- 引入layUI框架 -->
    <link rel="stylesheet" href="./layui/css/layui.css">
    <script src="./layui/layui.js"></script>
    <style>
        /* 全局样式重置 */
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow-x: hidden;
        }

        /* 修复模态框与页面重叠问题 */
        .layui-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
            width: 90%;
            max-width: 600px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 5px 15px rgba(0,0,0,.5);
        }

        /* 遮罩层样式 */
        .layui-modal-mask {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,.5);
            z-index: 999;
        }

        /* 自定义表格样式 */
        .layui-table {
            margin-top: 15px;
        }

        /* 操作按钮区样式 - 关键修改 */
        .operation-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
            align-items: center;
        }

        .search-container {
            flex: 1;
            min-width: 200px;
            display: flex;
            gap: 5px;
            align-items: center;
        }

        .search-input {
            flex: 1;
            max-width: 300px;
        }

        .btn-group {
            display: flex;
            gap: 5px;
            flex-wrap: nowrap;
        }

        /* 响应式调整 */
        @media screen and (max-width: 768px) {
            .operation-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .search-container {
                width: 100%;
            }

            .search-input {
                max-width: 100%;
            }

            .btn-group {
                width: 100%;
                flex-wrap: wrap;
            }

            .btn-group .layui-btn {
                flex: 1;
                margin-bottom: 5px;
            }

            .layui-input-inline {
                width: 100% !important;
                margin-right: 0 !important;
                margin-bottom: 10px;
            }

            .layui-modal {
                width: 95%;
            }
        }
    </style>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <!-- 顶部导航栏 -->
    <div class="layui-header">
        <div class="layui-logo">
            <i class="layui-icon layui-icon-cubes" style="font-size: 24px; color: #1E9FFF;"></i>
            <span style="margin-left: 5px;">仓仓管家</span>
        </div>

        <!-- 表切换菜单 -->
        <ul class="layui-nav layui-layout-left">
            <li class="layui-nav-item">
                <a href="javascript:;">切换表</a>
                <dl class="layui-nav-child">
                    <dd><a href="admin_user.html">人员表</a></dd>
                    <dd><a href="admin-good.html" class="layui-this">仓库表</a></dd>
                </dl>
            </li>
        </ul>

        <!-- 用户信息 -->
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">管理员</a>
            </li>
        </ul>
    </div>

    <!-- 主内容区 -->
    <div class="layui-body" style="padding: 15px; overflow: auto;">
        <!-- 操作按钮区 - 查询按钮移至右侧按钮组 -->
        <div class="layui-form-item operation-bar">
            <div class="search-container">
                <div class="layui-input-inline" style="width: 100%;">
                    <input type="number" id="searchInput" placeholder="输入商品ID搜索（100-10000之间）"
                           class="layui-input search-input">
                </div>
            </div>

            <div class="btn-group">
                <!-- 查询按钮移至右侧按钮组 -->
                <button id="searchBtn" class="layui-btn layui-btn-normal">
                    <i class="layui-icon layui-icon-search"></i> 查询商品
                </button>
                <button id="addGoodBtn" class="layui-btn">
                    <i class="layui-icon layui-icon-addition"></i> 增加商品
                </button>
                <button id="editGoodBtn" class="layui-btn layui-btn-warm" disabled>
                    <i class="layui-icon layui-icon-edit"></i> 编辑商品
                </button>
                <button id="deleteGoodBtn" class="layui-btn layui-btn-danger" disabled>
                    <i class="layui-icon layui-icon-delete"></i> 删除商品
                </button>
                <button id="refreshBtn" class="layui-btn layui-btn-primary">
                    <i class="layui-icon layui-icon-refresh"></i> 刷新
                </button>
            </div>
        </div>

        <!-- 商品表格 -->
        <div class="layui-table-responsive">
            <table class="layui-table" lay-size="sm">
                <thead>
                <tr>
                    <th style="width: 40px;">
                        <input type="checkbox" id="checkAll" lay-skin="primary">
                    </th>
                    <th>商品ID</th>
                    <th>商品名称</th>
                    <th>类别</th>
                    <th>品牌</th>
                    <th>型号</th>
                    <th>单价</th>
                    <th>库存数量</th>
                </tr>
                </thead>
                <tbody id="goodTableBody">
                <!-- 加载状态 -->
                <tr>
                    <td colspan="8" style="text-align: center; padding: 30px;">
                        <i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>
                        <span style="margin-left: 10px;">正在加载商品数据...</span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页控件 -->
        <div id="pagination" style="text-align: right; margin-top: 15px;"></div>
    </div>

    <!-- 页脚 -->
    <div class="layui-footer">
        © 仓仓管家 - 仓库管理系统
    </div>
</div>

<!-- 遮罩层 -->
<div id="modalMask" class="layui-modal-mask"></div>

<!-- 添加/编辑商品模态框 -->
<div id="goodModal" class="layui-modal" lay-title="商品信息">
    <div class="layui-modal-header">
        <span class="layui-modal-title">商品信息</span>
        <button class="layui-modal-close" id="closeModal">×</button>
    </div>
    <div class="layui-modal-content" style="padding: 20px;">
        <form class="layui-form" lay-filter="goodForm">
            <div class="layui-form-item">
                <label class="layui-form-label">商品ID</label>
                <div class="layui-input-block">
                    <input type="number" name="goodId" id="goodId" required
                           lay-verify="required|number|min(100)|max(10000)"
                           placeholder="请输入商品ID（100-10000之间）" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="goodName" id="goodName" required
                           lay-verify="required" placeholder="请输入商品名称" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品类别</label>
                <div class="layui-input-block">
                    <input type="text" name="goodCategory" id="goodCategory" required
                           lay-verify="required" placeholder="请输入商品类别" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品品牌</label>
                <div class="layui-input-block">
                    <input type="text" name="goodBrand" id="goodBrand" required
                           lay-verify="required" placeholder="请输入商品品牌" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品型号</label>
                <div class="layui-input-block">
                    <input type="text" name="goodModel" id="goodModel" required
                           lay-verify="required" placeholder="请输入商品型号" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品价格</label>
                <div class="layui-input-block">
                    <input type="number" step="0.01" min="0.01" name="goodPrice" id="goodPrice" required
                           lay-verify="required|number|min(0.01)" placeholder="请输入商品价格" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">库存数量</label>
                <div class="layui-input-block">
                    <input type="number" name="goodCount" id="goodCount" required
                           lay-verify="required|number|min(0)" placeholder="请输入库存数量" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="saveBtn">保存</button>
                    <button type="button" id="cancelBtn" class="layui-btn layui-btn-primary">取消</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    // 初始化layUI
    layui.use(['element', 'form', 'layer', 'laypage'], function() {
        const element = layui.element;
        const form = layui.form;
        const layer = layui.layer;
        const laypage = layui.laypage;

        // 后端API基础地址
        const API_BASE_URL = "http://localhost:8081/good";
        let currentGoodId = null; // 当前选中的商品ID
        let currentPage = 1;
        const pageSize = 10; // 前端分页每页数量
        let totalCount = 0; // 总数据量
        let currentSearchId = null;
        let allGoods = []; // 缓存所有商品数据（用于前端分页）

        // DOM元素缓存
        const goodTableBody = document.getElementById('goodTableBody');
        const searchInput = document.getElementById('searchInput');
        const addGoodBtn = document.getElementById('addGoodBtn');
        const editGoodBtn = document.getElementById('editGoodBtn');
        const deleteGoodBtn = document.getElementById('deleteGoodBtn');
        const searchBtn = document.getElementById('searchBtn');
        const refreshBtn = document.getElementById('refreshBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const goodModal = document.getElementById('goodModal');
        const modalMask = document.getElementById('modalMask');
        const closeModalBtn = document.getElementById('closeModal');
        const layuiBody = document.querySelector('.layui-body');

        // 页面初始化
        init();

        // 初始化函数
        function init() {
            loadAllGoods(); // 加载所有商品，前端分页
            setupEventListeners();
        }

        // 设置事件监听
        function setupEventListeners() {
            // 添加商品
            addGoodBtn.addEventListener('click', () => {
                currentGoodId = null;
                form.val('goodForm', {
                    goodId: '',
                    goodName: '',
                    goodCategory: '',
                    goodBrand: '',
                    goodModel: '',
                    goodPrice: '',
                    goodCount: ''
                });
                openModal('添加商品');
            });

            // 编辑商品
            editGoodBtn.addEventListener('click', () => {
                if (!currentGoodId) return;

                fetch(`${API_BASE_URL}/${currentGoodId}`, {
                    method: 'GET',
                    credentials: 'include'
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP错误，状态码: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.code === 200 && data.data) {
                            const good = data.data;
                            form.val('goodForm', {
                                goodId: good.goodId,
                                goodName: good.goodName,
                                goodCategory: good.goodCategory || '',
                                goodBrand: good.goodBrand || '',
                                goodModel: good.goodModel || '',
                                goodPrice: good.goodPrice || '',
                                goodCount: good.goodCount || ''
                            });
                            openModal('编辑商品');
                        } else {
                            layer.msg(data.message || '获取商品信息失败', {icon: 5});
                        }
                    })
                    .catch(error => {
                        console.error('编辑商品失败:', error);
                        layer.msg(`获取商品信息失败: ${error.message}`, {icon: 5});
                    });
            });

            // 删除商品
            deleteGoodBtn.addEventListener('click', () => {
                if (!currentGoodId) return;

                layer.confirm(`确定要删除商品 #${currentGoodId} 吗？`, {
                    title: '确认删除',
                    icon: 3
                }, function(index) {
                    layer.close(index);

                    fetch(`${API_BASE_URL}/${currentGoodId}`, {
                        method: 'DELETE',
                        credentials: 'include'
                    })
                        .then(response => {
                            if (!response.ok) {
                                return response.json().then(err => {
                                    throw new Error(err.message || `删除失败，状态码: ${response.status}`);
                                });
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.code === 200) {
                                layer.msg('商品删除成功', {icon: 1});
                                currentGoodId = null;
                                updateButtonStates();
                                loadAllGoods();
                            } else {
                                throw new Error(data.message || '删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('删除商品失败:', error);
                            layer.msg(error.message, {icon: 5});
                        });
                });
            });

            // 搜索商品
            searchBtn.addEventListener('click', searchGood);
            searchInput.addEventListener('keyup', (e) => {
                if (e.key === 'Enter') searchGood();
            });

            // 刷新
            refreshBtn.addEventListener('click', () => {
                currentSearchId = null;
                searchInput.value = '';
                currentPage = 1;
                currentGoodId = null;
                updateButtonStates();
                loadAllGoods();
            });

            // 取消按钮
            cancelBtn.addEventListener('click', closeModalDialog);

            // 关闭模态框
            closeModalBtn.addEventListener('click', closeModalDialog);

            // 点击遮罩层关闭模态框
            modalMask.addEventListener('click', closeModalDialog);

            // 全选/取消全选
            form.on('checkbox(#checkAll)', function(data) {
                const checked = data.elem.checked;
                document.querySelectorAll('tbody [type="checkbox"]').forEach(checkbox => {
                    checkbox.checked = checked;
                });
                form.render('checkbox');

                if (checked && goodTableBody.querySelectorAll('tr').length > 0) {
                    const firstGoodId = goodTableBody.querySelector('tr').getAttribute('data-id');
                    currentGoodId = firstGoodId ? parseInt(firstGoodId) : null;
                } else {
                    currentGoodId = null;
                }
                updateButtonStates();
            });

            // 监听保存按钮
            form.on('submit(saveBtn)', function(data) {
                saveGood(data.field);
                return false;
            });

            // 监听表格行点击事件
            goodTableBody.addEventListener('click', function(e) {
                const target = e.target;
                const checkbox = target.closest('[type="checkbox"]');

                if (checkbox) return;

                const tr = target.closest('tr');
                if (tr && tr.getAttribute('data-id')) {
                    document.querySelectorAll('tbody [type="checkbox"]').forEach(cb => {
                        cb.checked = false;
                    });
                    const currentCheckbox = tr.querySelector('[type="checkbox"]');
                    if (currentCheckbox) {
                        currentCheckbox.checked = true;
                        currentGoodId = parseInt(tr.getAttribute('data-id'));
                        form.render('checkbox');
                        updateButtonStates();
                    }
                }
            });

            // 窗口大小变化时调整模态框位置
            window.addEventListener('resize', adjustModalPosition);
        }

        // 搜索商品
        function searchGood() {
            const searchValue = searchInput.value.trim();

            if (!searchValue) {
                currentSearchId = null;
                currentPage = 1;
                renderPagedGoods(allGoods);
                return;
            }

            const goodId = parseInt(searchValue);
            if (isNaN(goodId) || goodId < 100 || goodId > 10000) {
                layer.tips('请输入100-10000之间的商品ID', searchInput, {
                    tips: [1, '#FF5722']
                });
                return;
            }

            fetch(`${API_BASE_URL}/${goodId}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 404) {
                            renderPagedGoods([]);
                            return;
                        }
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200 && data.data) {
                        currentSearchId = goodId;
                        renderPagedGoods([data.data]);
                    } else {
                        renderPagedGoods([]);
                    }
                })
                .catch(error => {
                    console.error('搜索商品失败:', error);
                    layer.msg(`搜索失败: ${error.message}`, {icon: 5});
                });
        }

        // 加载所有商品
        function loadAllGoods() {
            goodTableBody.innerHTML = `
                <tr>
                    <td colspan="8" style="text-align: center; padding: 30px;">
                        <i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>
                        <span style="margin-left: 10px;">正在加载商品数据...</span>
                    </td>
                </tr>
            `;

            fetch(API_BASE_URL, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        allGoods = data.data || [];
                        renderPagedGoods(allGoods);
                    } else {
                        throw new Error(data.message || '获取商品列表失败');
                    }
                })
                .catch(error => {
                    console.error('加载商品失败:', error);
                    goodTableBody.innerHTML = `
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 30px; color: #FF5722;">
                                <i class="layui-icon layui-icon-info-circle"></i>
                                <span style="margin-left: 10px;">${error.message}</span>
                            </td>
                        </tr>
                    `;
                });
        }

        // 渲染分页后的商品列表
        function renderPagedGoods(goods) {
            totalCount = goods.length;
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pagedGoods = goods.slice(startIndex, endIndex);

            goodTableBody.innerHTML = '';

            if (pagedGoods.length === 0) {
                goodTableBody.innerHTML = `
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 30px;">
                            <i class="layui-icon layui-icon-search" style="font-size: 24px; color: #999;"></i>
                            <span style="margin-left: 10px; color: #999;">没有找到匹配的商品</span>
                        </td>
                    </tr>
                `;
                renderPagination();
                return;
            }

            pagedGoods.forEach(good => {
                const row = document.createElement('tr');
                row.setAttribute('data-id', good.goodId);
                const isChecked = currentGoodId === good.goodId ? 'checked' : '';

                row.innerHTML = `
                    <td>
                        <input type="checkbox" name="goodCheck" lay-skin="primary" ${isChecked}>
                    </td>
                    <td>${good.goodId}</td>
                    <td>${good.goodName}</td>
                    <td>${good.goodCategory || '-'}</td>
                    <td>${good.goodBrand || '-'}</td>
                    <td>${good.goodModel || '-'}</td>
                    <td>¥${good.goodPrice}</td>
                    <td>${good.goodCount}</td>
                `;
                goodTableBody.appendChild(row);
            });

            form.render('checkbox');
            renderPagination();
        }

        // 保存商品
        function saveGood(goodData) {
            const payload = {
                goodId: parseInt(goodData.goodId),
                goodName: goodData.goodName.trim(),
                goodCategory: goodData.goodCategory.trim(),
                goodBrand: goodData.goodBrand.trim(),
                goodModel: goodData.goodModel.trim(),
                goodPrice: parseFloat(goodData.goodPrice),
                goodCount: parseInt(goodData.goodCount)
            };

            const method = currentGoodId ? 'PUT' : 'POST';

            fetch(API_BASE_URL, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(payload),
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.message || `操作失败，状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        closeModalDialog();
                        layer.msg(currentGoodId ? '商品更新成功' : '商品添加成功', {icon: 1});
                        loadAllGoods();
                    } else {
                        throw new Error(data.message || '操作失败');
                    }
                })
                .catch(error => {
                    console.error('保存商品失败:', error);
                    layer.msg(error.message, {icon: 5});
                });
        }

        // 打开模态框
        function openModal(title) {
            document.querySelector('#goodModal .layui-modal-title').innerText = title;
            goodModal.style.display = 'block';
            modalMask.style.display = 'block';

            if (currentGoodId) {
                document.getElementById('goodId').setAttribute('disabled', 'disabled');
            } else {
                document.getElementById('goodId').removeAttribute('disabled');
            }

            layuiBody.style.overflow = 'hidden';
            adjustModalPosition();
        }

        // 关闭模态框
        function closeModalDialog() {
            goodModal.style.display = 'none';
            modalMask.style.display = 'none';
            layuiBody.style.overflow = '';
        }

        // 调整模态框位置
        function adjustModalPosition() {
            if (goodModal.style.display !== 'none') {
                const windowHeight = window.innerHeight;
                const modalHeight = goodModal.offsetHeight;

                if (modalHeight > windowHeight * 0.9) {
                    goodModal.style.maxHeight = `${windowHeight * 0.9}px`;
                    goodModal.style.overflowY = 'auto';
                } else {
                    goodModal.style.maxHeight = '';
                    goodModal.style.overflowY = '';
                }
            }
        }

        // 更新按钮状态
        function updateButtonStates() {
            const hasSelected = currentGoodId !== null;
            editGoodBtn.disabled = !hasSelected;
            deleteGoodBtn.disabled = !hasSelected;

            if (hasSelected) {
                editGoodBtn.classList.remove('layui-btn-disabled');
                deleteGoodBtn.classList.remove('layui-btn-disabled');
            } else {
                editGoodBtn.classList.add('layui-btn-disabled');
                deleteGoodBtn.classList.add('layui-btn-disabled');
            }
        }

        // 渲染分页
        function renderPagination() {
            laypage.render({
                elem: 'pagination',
                count: totalCount,
                limit: pageSize,
                curr: currentPage,
                layout: ['prev', 'page', 'next', 'count'],
                jump: function(obj, first) {
                    if (!first) {
                        currentPage = obj.curr;
                        const targetGoods = currentSearchId ? allGoods.filter(g => g.goodId === currentSearchId) : allGoods;
                        renderPagedGoods(targetGoods);
                    }
                }
            });
        }
    });
</script>
</body>
</html>